import React, { useState, useEffect } from 'react';
import './index.less';
import { useAsyncEffect } from 'ahooks';
import { getFetch } from '@/utils/doFetch';
import wx from 'weixin-js-sdk';

function Speak({ speak = false, setSpeak, message_content, server }) {
  const res = message_content ? JSON.parse(message_content) : null;
  const { localId, serverId } = res ?? {};

  useAsyncEffect(async () => {
    let res = await getFetch({
      url: '/wbn-api/wechat/signature',
      params: { url: document.URL },
    });
    if (res.code == 0) {
      wx.config({
        debug: false,
        appId: res.data.app_id,
        timestamp: res.data.timestamp,
        nonceStr: res.data.nonce_str,
        signature: res.data.signature,
        jsApiList: [
          'startRecord',
          'stopRecord',
          'onVoiceRecordEnd',
          'uploadVoice',
          'downloadVoice',
          'playVoice',
          'stopVoice',
          'onVoicePlayEnd',
        ], // 需要使用的API列表
      });

      //ready之后
      wx.onVoicePlayEnd({
        complete: () => {
          setSpeak(null);
        },
      });

      wx.error(function () {});
    }
  }, []);

  const ifs = server ? speak === serverId : speak === localId;

  const [sl, setSl] = useState(null);

  return (
    <div
      className={`center dark`}
      style={{ gap: 12 }}
      onClick={() => {
        if (speak) {
          wx.stopVoice({
            localId: sl ?? speak,
          });
          setSpeak(null);
          return;
        }

        if (server) {
          //对方发送的消息 先下载后播放 唯一key
          wx.downloadVoice({
            serverId: serverId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
              var localId = res.localId; // 返回音频的本地ID
              wx.playVoice({
                localId: localId,
              });
              setSl(localId);
              setSpeak(serverId);
            },
          });
        } else {
          wx.playVoice({
            localId: localId,
          });
          setSpeak(localId);
        }
      }}
    >
      {ifs && speak ? (
        <div className="loader">
          <span className="bar" />
          <span className="bar" />
          <span className="bar" />
        </div>
      ) : (
        <div className="loaders">
          <span className="bars" />
          <span className="bars" />
          <span className="bars" />
        </div>
      )}
      <span className="txt">语音消息</span>
    </div>
  );
}

export default Speak;
